from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAdminUser
from datetime import date, timedelta

from goods.models import GoodsVisitCount
from meiduo_admin.serlizer.statistical import GoodsSerializer
from users.models import User


class UserCountView(APIView):
    '''用户总量统计'''

    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1. 获取当天日期
        now_date = date.today()
        # 2. 获取用户总量
        count = User.objects.all().count()
        # 3. 返回结果
        return Response({
            'date': now_date,
            'count': count
        })


class UserDayCountView(APIView):
    '''日增用户统计'''
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1. 获取当天日期
        now_date = date.today()
        # 2. 获取日曾用户总量
        count = User.objects.filter(date_joined__gte=now_date).count()
        # 3. 返回结果
        return Response({
            'date': now_date,
            'count': count
        })


class UserActiveCount(APIView):
    '''日活用户数量'''
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1. 获取当天日期
        now_date = date.today()
        # 2. 获取日曾用户总量
        count = User.objects.filter(last_login__gte=now_date).count()
        # 3. 返回结果
        return Response({
            'date': now_date,
            'count': count
        })


class UserOrderCount(APIView):
    '''日下单数量'''
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1. 获取当天日期
        now_date = date.today()
        # 2. 获取日曾用户总量
        count = User.objects.filter(orders__create_time__gte=now_date).count()
        # 3. 返回结果
        return Response({
            'date': now_date,
            'count': count
        })


class UserOrderMonthCount(APIView):
    '''月注册数量'''
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 1. 获取当天日期
        now_date = date.today()
        # 获取一个月前的日期
        begin_date = now_date - timedelta(days=29)
        date_list = []
        for i in range(30):
            # 开始日期
            index_date = begin_date + timedelta(days=i)
            # 第二天日期
            next_date = begin_date + timedelta(days=i+1)
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=next_date).count()
            date_list.append({
                'count': count,
                'date': index_date
            })
        # 3. 返回结果
        return Response(date_list)



class GoodsDayView(APIView):
    '''日分类商品访问量'''
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当天日期
        now_date=date.today()
        # 获取当天访问的商品分类数量信息
        data = GoodsVisitCount.objects.filter(date=now_date)
        # 序列化返回分类数量
        ser = GoodsSerializer(data, many=True)

        return Response(ser.data)